import os
import sqlite3
import json
from app import create_app, db

def migrate_database():
    """更新数据库结构以支持BO3/BO5赛制、蓝红方和详细盈利信息，并修复teams表结构"""
    app = create_app()
    
    with app.app_context():
        db_path = os.path.join(app.instance_path, 'esports.db')
        if not os.path.exists(db_path):
            print("数据库文件不存在")
            return
        
        # 使用SQLite直接连接执行ALTER TABLE语句
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        
        try:
            # 修复teams表结构
            team_columns = [row[1] for row in cursor.execute("PRAGMA table_info(teams)")]
            
            # 添加缺失的teams表字段
            if "league" not in team_columns:
                cursor.execute("ALTER TABLE teams ADD COLUMN league VARCHAR(100) DEFAULT 'LCK'")
                print("添加了teams.league字段")
            
            if "game" not in team_columns:
                cursor.execute("ALTER TABLE teams ADD COLUMN game VARCHAR(100) DEFAULT 'lol'")
                print("添加了teams.game字段")
            
            if "icon" not in team_columns:
                cursor.execute("ALTER TABLE teams ADD COLUMN icon VARCHAR(255) DEFAULT 'default_team.png'")
                print("添加了teams.icon字段")
            
            # 处理matches表结构
            match_columns = [row[1] for row in cursor.execute("PRAGMA table_info(matches)")]
            
            # 添加game_type字段
            if "game_type" not in match_columns:
                cursor.execute("ALTER TABLE matches ADD COLUMN game_type VARCHAR(50) DEFAULT 'lol'")
                print("添加了matches.game_type字段")
            
            # 添加新列或修改列名
            if "investment" not in match_columns and "profit" in match_columns:
                # 获取所有match记录
                cursor.execute("SELECT id, profit FROM matches")
                matches_profit = cursor.fetchall()
                
                # 创建新列
                cursor.execute("ALTER TABLE matches ADD COLUMN investment FLOAT DEFAULT 0")
                cursor.execute("ALTER TABLE matches ADD COLUMN return_amount FLOAT DEFAULT 0")
                
                # 迁移数据 (假设profit是回报与投资的差值，投资默认为100)
                for match_id, profit in matches_profit:
                    investment = 100  # 默认投资
                    return_amount = investment + profit
                    cursor.execute(
                        "UPDATE matches SET investment = ?, return_amount = ? WHERE id = ?",
                        (investment, return_amount, match_id)
                    )
            
            # 添加其他新列
            if "match_format" not in match_columns:
                cursor.execute("ALTER TABLE matches ADD COLUMN match_format TEXT DEFAULT 'Bo3'")
            
            if "team1_blue_side" not in match_columns:
                cursor.execute("ALTER TABLE matches ADD COLUMN team1_blue_side INTEGER DEFAULT 1")
            
            if "total_games" not in match_columns:
                cursor.execute("ALTER TABLE matches ADD COLUMN total_games INTEGER DEFAULT 3")
            
            if "games_json" not in match_columns:
                cursor.execute("ALTER TABLE matches ADD COLUMN games_json TEXT DEFAULT '{}'")
            
            # 为每个现有比赛记录创建默认的games_json数据
            if "investment" in match_columns and "return_amount" in match_columns:
                cursor.execute("SELECT id, investment, return_amount FROM matches")
            else:
                cursor.execute("SELECT id, 100 as investment, profit + 100 as return_amount FROM matches")
                
            matches = cursor.fetchall()
            
            for match_id, investment, return_amount in matches:
                # 创建一个简单的默认游戏数据结构
                games_data = {
                    "games": [
                        {
                            "game_number": 1,
                            "blue_side": True,  # 主队为蓝方
                            "investment": investment / 3,  # 平均分配到每场比赛
                            "return_amount": return_amount / 3
                        },
                        {
                            "game_number": 2,
                            "blue_side": False,  # 主队为红方
                            "investment": investment / 3,
                            "return_amount": return_amount / 3
                        },
                        {
                            "game_number": 3,
                            "blue_side": True,  # 主队为蓝方
                            "investment": investment / 3,
                            "return_amount": return_amount / 3
                        }
                    ]
                }
                
                # 更新记录
                cursor.execute(
                    "UPDATE matches SET games_json = ? WHERE id = ?",
                    (json.dumps(games_data), match_id)
                )
                
            # 更新团队联赛信息（如果联赛字段是数字）
            cursor.execute("SELECT id, league FROM teams")
            teams = cursor.fetchall()
            
            for team_id, league_value in teams:
                try:
                    # 检查league是否是数字
                    int(league_value)
                    # 如果是数字，更新为合适的联赛名称
                    if team_id <= 3:  # 根据之前的检查，前3个队伍是T1, GEN, DRX
                        cursor.execute(
                            "UPDATE teams SET league = ?, game = ? WHERE id = ?",
                            ("LCK", "lol", team_id)
                        )
                except (ValueError, TypeError):
                    # 不是数字，无需更新
                    pass
            
            conn.commit()
            print("数据库迁移成功！")
            
        except Exception as e:
            conn.rollback()
            print(f"迁移失败: {str(e)}")
        finally:
            conn.close()

if __name__ == "__main__":
    migrate_database() 